"""
认证相关API - 模块化版本
API位置: app/api/v1/auth.py
访问路径: /api/v1/auth/
"""
from flask import request
from flask_restx import Resource, fields
from app.models import User, db
from app.utils.auth import generate_token
from app.utils.response import success_response, error_response
from app.utils.validators import validate_phone, validate_email, validate_password
from datetime import datetime
from . import auth_ns

# 定义数据模型
login_model = auth_ns.model('Login', {
    'username': fields.String(required=True, description='用户名'),
    'password': fields.String(required=True, description='密码')
})

register_model = auth_ns.model('Register', {
    'username': fields.String(required=True, description='用户名'),
    'password': fields.String(required=True, description='密码'),
    'phone': fields.String(required=True, description='手机号'),
    'email': fields.String(description='邮箱')
})

@auth_ns.route('/login')
class Login(Resource):
    @auth_ns.expect(login_model)
    @auth_ns.doc('用户登录')
    def post(self):
        """用户登录"""
        data = request.get_json()
        
        if not data or 'username' not in data or 'password' not in data:
            return error_response('用户名和密码不能为空', 400)
        
        username = data['username']
        password = data['password']
        
        # 查找用户
        user = User.query.filter_by(username=username).first()
        
        if not user or not user.check_password(password):
            return error_response('用户名或密码错误', 401)
        
        if not user.is_active:
            return error_response('账户已被禁用', 403)
        
        # 更新最后登录时间
        user.last_login = datetime.utcnow()
        db.session.commit()
        
        # 生成token
        token = generate_token(user.id)
        
        return success_response({
            'userid': user.id,
            'username': user.username,
            'phone': user.phone,
            'email': user.email,
            'token': token,
            'last_login': user.last_login.isoformat()
        }, '登录成功')

@auth_ns.route('/register')
class Register(Resource):
    @auth_ns.expect(register_model)
    @auth_ns.doc('用户注册')
    def post(self):
        """用户注册"""
        data = request.get_json()
        
        if not data or 'username' not in data or 'password' not in data or 'phone' not in data:
            return error_response('用户名、密码和手机号不能为空', 400)
        
        username = data['username']
        password = data['password']
        phone = data['phone']
        email = data.get('email')
        
        # 验证密码
        is_valid, msg = validate_password(password)
        if not is_valid:
            return error_response(msg, 400)
        
        # 验证手机号
        if not validate_phone(phone):
            return error_response('手机号格式不正确', 400)
        
        # 验证邮箱
        if email and not validate_email(email):
            return error_response('邮箱格式不正确', 400)
        
        # 检查用户是否已存在
        if User.query.filter_by(username=username).first():
            return error_response('用户名已存在', 400)
        
        if User.query.filter_by(phone=phone).first():
            return error_response('手机号已存在', 400)
        
        if email and User.query.filter_by(email=email).first():
            return error_response('邮箱已存在', 400)
        
        # 创建新用户
        user = User(username=username, phone=phone, email=email)
        user.set_password(password)
        
        db.session.add(user)
        db.session.commit()
        
        return success_response({
            'userid': user.id,
            'username': user.username,
            'phone': user.phone,
            'email': user.email
        }, '注册成功', 200)
